﻿using DingTalk.Api;
using DingTalk.Api.Request;
using DingTalk.Api.Response;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace KPI_SYSTEM.Code
{
    public static class DingHelper
    {
        private static String _appkey = System.Configuration.ConfigurationManager.AppSettings["AppKey"];
        private static String _appsecret = System.Configuration.ConfigurationManager.AppSettings["AppSecret"];
        private static String _corpId = System.Configuration.ConfigurationManager.AppSettings["CorpId"];
        private static String _agentId = System.Configuration.ConfigurationManager.AppSettings["AgentId"];
        /// <summary>
        ///  根据Appkey、Appsecret获取会话token
        /// </summary>
        /// <returns></returns>
        public static String TestGetToken()
        {
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest request = new OapiGettokenRequest();
            request.Appkey = _appkey;
            request.Appsecret = _appsecret;
            request.SetHttpMethod("GET");
            OapiGettokenResponse response = client.Execute(request);
            return JsonHelper.JsonSerializer<OapiGettokenResponse>(response);
        }
        /// <summary>
        ///  根据Appkey、Appsecret获取会话token
        /// </summary>
        /// <returns></returns>
        public static OapiGettokenResponse GetToken()
        {
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest request = new OapiGettokenRequest();
            request.Appkey = _appkey;
            request.Appsecret = _appsecret;
            request.SetHttpMethod("GET");
            OapiGettokenResponse response = client.Execute(request);
            return response;
        }
        /// <summary>
        /// 添加部门
        /// </summary>
        /// <param name="name">部门名称</param>
        /// <returns></returns>
        public static String AddDept(String name)
        {
            OapiGettokenResponse oapiGettokenResponse = GetToken();
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/create");
            OapiDepartmentCreateRequest request = new OapiDepartmentCreateRequest();
            request.Parentid = "1";
            request.Order = "1";
            request.Name = name;
            OapiDepartmentCreateResponse response = client.Execute(request, oapiGettokenResponse.AccessToken);
            return JsonHelper.JsonSerializer<OapiDepartmentCreateResponse>(response);
        }


        /// <summary>
        /// 根据DEPTID获取部门详细信息
        /// </summary>
        /// <param name="DeptID"></param>
        /// <returns></returns>
        public static String GetDeptDetailMessage(String DeptID)
        {
            OapiGettokenResponse oapiGettokenResponse = GetToken();
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/get");
            OapiDepartmentGetRequest request = new OapiDepartmentGetRequest();
            request.Id= DeptID;
            request.SetHttpMethod("GET");
            OapiDepartmentGetResponse response = client.Execute(request, oapiGettokenResponse.AccessToken);
            return JsonHelper.JsonSerializer<OapiDepartmentGetResponse>(response);
        }
        /// <summary>
        /// 获取部门ID列表
        /// </summary>
        /// <returns></returns>
        public static String GetDeptIDList()
        {
            OapiGettokenResponse oapiGettokenResponse = GetToken();
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/list_ids");
            OapiDepartmentListIdsRequest request = new OapiDepartmentListIdsRequest();
            request.Id = "1";
            request.SetHttpMethod("GET");
            OapiDepartmentListIdsResponse response = client.Execute(request, oapiGettokenResponse.AccessToken);
            return JsonHelper.JsonSerializer<OapiDepartmentListIdsResponse>(response);
        }
        /// <summary>
        /// 根据部门ID获取用户列表
        /// </summary>
        /// <param name="deptID">部门ID</param>
        /// <returns></returns>
        public static String GetUserListByDept(String deptID)
        {
            OapiGettokenResponse oapiGettokenResponse = GetToken();
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/simplelist");
            OapiUserSimplelistRequest request = new OapiUserSimplelistRequest();
            request.DepartmentId = Convert.ToInt32(deptID);
            request.SetHttpMethod("GET");
            OapiUserSimplelistResponse response = client.Execute(request, oapiGettokenResponse.AccessToken);
            return JsonHelper.JsonSerializer<OapiUserSimplelistResponse>(response);
        }
        /// <summary>
        /// 根据部门ID获取用户ID列表
        /// </summary>
        /// <param name="deptID">部门ID</param>
        /// <returns></returns>
        public static String GetUserIDListByDept(String deptID)
        {
            OapiGettokenResponse oapiGettokenResponse = GetToken();
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getDeptMember");
            OapiUserGetDeptMemberRequest request = new OapiUserGetDeptMemberRequest();
            request.DeptId = deptID;
            request.SetHttpMethod("GET");
            OapiUserGetDeptMemberResponse response = client.Execute(request, oapiGettokenResponse.AccessToken);
            return JsonHelper.JsonSerializer<OapiUserGetDeptMemberResponse>(response); ;
        }
        /// <summary>
        /// 发送消息给用户
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static String SendMessageToUser(String message, String UserID)
        {
            OapiGettokenResponse oapiGettokenResponse = GetToken();
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
            //通过DeptID获取该部门UserId列表
            //OapiUserGetDeptMemberResponse UserIdsModel = JsonHelper.JsonDeserialize<OapiUserGetDeptMemberResponse>(GetUserIDListByDept(deptId));
            request.UseridList = UserID;
            request.AgentId = Convert.ToInt64(_agentId);
            request.ToAllUser = false;
            request.SetHttpMethod("POST");

            OapiMessageCorpconversationAsyncsendV2Request.MsgDomain msg = new OapiMessageCorpconversationAsyncsendV2Request.MsgDomain();
            msg.Msgtype = "text";
            msg.Text = new OapiMessageCorpconversationAsyncsendV2Request.TextDomain();
            msg.Text.Content = message;
            request.Msg_ = msg;
            OapiMessageCorpconversationAsyncsendV2Response response = client.Execute(request, oapiGettokenResponse.AccessToken);
            return JsonConvert.SerializeObject(response);
        }

        /// <summary>
        /// 得到当前用户ID
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static String GetUserId(String code)
        {
            OapiGettokenResponse oapiGettokenResponse = GetToken();
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getuserinfo");
            OapiUserGetuserinfoRequest request = new OapiUserGetuserinfoRequest();
            request.Code = code;
            request.SetHttpMethod("GET");
            OapiUserGetuserinfoResponse response = client.Execute(request, oapiGettokenResponse.AccessToken);
            return response.Userid;
        }
        /// <summary>
        /// 得到当前用户ID
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static String TestGetUserId(String code)
        {
            OapiGettokenResponse oapiGettokenResponse = GetToken();
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getuserinfo");
            OapiUserGetuserinfoRequest request = new OapiUserGetuserinfoRequest();
            request.Code = code;
            request.SetHttpMethod("GET");
            OapiUserGetuserinfoResponse response = client.Execute(request, oapiGettokenResponse.AccessToken);
            return JsonHelper.JsonSerializer<OapiUserGetuserinfoResponse>(response);
        }
        /// <summary>
        /// 根据用户ID获取用户详细信息
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public static DING_USER_INFO GetUserDetailMessage(String UserID)
        {
            DING_USER_INFO dING_USER_INFO = new DING_USER_INFO();
            OapiGettokenResponse oapiGettokenResponse = GetToken();
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get");
            OapiUserGetRequest request = new OapiUserGetRequest();
            request.Userid = UserID;
            request.SetHttpMethod("GET");
            OapiUserGetResponse response = client.Execute(request, oapiGettokenResponse.AccessToken);
            JObject jObjectUser = JObject.Parse(response.Body);
            if (jObjectUser["errcode"].ToString() == "0")
            {
                dING_USER_INFO.USER_DING_ID = jObjectUser["userid"].ToString();
                if (jObjectUser["jobnumber"] != null)
                {
                    dING_USER_INFO.USER_CODE = jObjectUser["jobnumber"].ToString();
                }
                else
                {
                    dING_USER_INFO.USER_CODE = "暂无";
                }
                dING_USER_INFO.USER_NAME = jObjectUser["name"].ToString();
                String DeptID = "";
                foreach (var itemDept in jObjectUser["department"])
                {
                    DeptID += itemDept.ToString() + ",";
                }
                dING_USER_INFO.USER_DEPT = DeptID.ToString().TrimEnd(',');
                if (jObjectUser["position"] != null)
                {
                    dING_USER_INFO.USER_POSITION = jObjectUser["position"].ToString();
                }
                else
                {
                    dING_USER_INFO.USER_POSITION = "暂无";
                }
                if (jObjectUser["mobile"] != null)
                {
                    dING_USER_INFO.USER_PHONE = jObjectUser["mobile"].ToString();
                }
                else
                {
                    dING_USER_INFO.USER_PHONE = "暂无";
                }
                String RoleID = "";
                if (jObjectUser["roles"] != null)
                {
                    foreach (var itemRole in jObjectUser["roles"])
                    {
                        RoleID += itemRole["id"].ToString() + ",";
                    }
                    dING_USER_INFO.USER_ROLE = RoleID.ToString().TrimEnd(',');
                }
                else
                {
                    dING_USER_INFO.USER_ROLE = "0";
                }
            }
            return dING_USER_INFO;
        }
        /// <summary>
        /// 获取部门列表
        /// </summary>
        /// <returns></returns>
        public static List<DING_DEPT_INFO> GetDeptList()
        {
            List<DING_DEPT_INFO> dEPT_INFOs = new List<DING_DEPT_INFO>();
            OapiGettokenResponse oapiGettokenResponse = GetToken();
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/list");
            OapiDepartmentListRequest request = new OapiDepartmentListRequest();
            request.Id = "1";
            request.SetHttpMethod("GET");
            OapiDepartmentListResponse response = client.Execute(request, oapiGettokenResponse.AccessToken);
            JObject jObject = JObject.Parse(response.Body);
            if (jObject["errcode"].ToString() == "0")
            {
                foreach (var item in jObject["department"])
                {
                    DING_DEPT_INFO dEPT_INFO = new DING_DEPT_INFO();
                    dEPT_INFO.DING_CODE = item["id"].ToString();
                    dEPT_INFO.DEPT_NAME = item["name"].ToString();
                    dEPT_INFO.PARENT_ID = item["parentid"].ToString();
                    dEPT_INFOs.Add(dEPT_INFO);
                }
            }
            return dEPT_INFOs;
        }
        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <returns></returns>
        public static List<DING_ROLE_INFO> GetRoleList()
        {
            List<DING_ROLE_INFO> rOLE_INFOs = new List<DING_ROLE_INFO>();
            OapiGettokenResponse oapiGettokenResponse = GetToken();
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/role/list");
            OapiRoleListRequest request = new OapiRoleListRequest();
            request.Size = 199;
            OapiRoleListResponse response = client.Execute(request, oapiGettokenResponse.AccessToken);
            JObject jObject = JObject.Parse(response.Body);
            if (jObject["errcode"].ToString() == "0")
            {
                
                foreach (var groupItem in jObject["result"]["list"])
                {
                   
                    foreach (var roleItem in groupItem["roles"])
                    {
                        DING_ROLE_INFO rOLE_INFO = new DING_ROLE_INFO();
                        rOLE_INFO.ROLE_GROUP_NAME = groupItem["name"].ToString();
                        rOLE_INFO.ROLE_GROUP_ID = groupItem["groupId"].ToString();
                        rOLE_INFO.ROLE_ID = roleItem["id"].ToString();
                        rOLE_INFO.ROLE_NAME = roleItem["name"].ToString();
                        rOLE_INFOs.Add(rOLE_INFO);
                    }
                }
                
            }
            return rOLE_INFOs;
        }
        public static List<DING_USER_INFO> GetUserList()
        {
            List<DING_USER_INFO> dING_USER_INFOs = new List<DING_USER_INFO>();
            OapiGettokenResponse oapiGettokenResponse = GetToken();

            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/list");
            OapiDepartmentListRequest request = new OapiDepartmentListRequest();
            request.Id = "1";
            request.SetHttpMethod("GET");
            OapiDepartmentListResponse response = client.Execute(request, oapiGettokenResponse.AccessToken);
            JObject jObject = JObject.Parse(response.Body);
            if (jObject["errcode"].ToString() == "0")
            {
                foreach (var item in jObject["department"])
                {
                    String deptID = item["id"].ToString();
                    IDingTalkClient clientUserID = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getDeptMember");
                    OapiUserGetDeptMemberRequest requestUserID = new OapiUserGetDeptMemberRequest();
                    requestUserID.DeptId = deptID;
                    requestUserID.SetHttpMethod("GET");
                    OapiUserGetDeptMemberResponse responseUserID = clientUserID.Execute(requestUserID, oapiGettokenResponse.AccessToken);
                    JObject jObjectUserID = JObject.Parse(responseUserID.Body);
                    if (jObjectUserID["errcode"].ToString() == "0")
                    {
                        if (jObjectUserID["userIds"].Count() > 0)
                        {
                            foreach (var itemUserID in jObjectUserID["userIds"])
                            {
                                IDingTalkClient clientUser = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get");
                                OapiUserGetRequest requestUser = new OapiUserGetRequest();
                                requestUser.Userid = itemUserID.ToString();
                                requestUser.SetHttpMethod("GET");
                                OapiUserGetResponse responseUser = clientUser.Execute(requestUser, oapiGettokenResponse.AccessToken);
                                JObject jObjectUser = JObject.Parse(responseUser.Body);
                                if (jObjectUser["errcode"].ToString() == "0")
                                {
                                    DING_USER_INFO dING_USER_INFO = new DING_USER_INFO();
                                    if (dING_USER_INFOs.Where(t => t.USER_DING_ID == jObjectUser["userid"].ToString()).Count() <= 0)
                                    {
                                        dING_USER_INFO.USER_DING_ID = jObjectUser["userid"].ToString();
                                        if (jObjectUser["jobnumber"] != null)
                                        {
                                            dING_USER_INFO.USER_CODE = jObjectUser["jobnumber"].ToString();
                                        }
                                        else
                                        {
                                            dING_USER_INFO.USER_CODE = "暂无";
                                        }
                                        dING_USER_INFO.USER_NAME = jObjectUser["name"].ToString();
                                        String DeptID = "";
                                        foreach (var itemDept in jObjectUser["department"])
                                        {
                                            DeptID += itemDept.ToString() + ",";
                                        }
                                        dING_USER_INFO.USER_DEPT = DeptID.ToString().TrimEnd(',');
                                        if (jObjectUser["position"] != null)
                                        {
                                            dING_USER_INFO.USER_POSITION = jObjectUser["position"].ToString();
                                        }
                                        else
                                        {
                                            dING_USER_INFO.USER_POSITION = "暂无";
                                        }
                                        if (jObjectUser["mobile"] != null)
                                        {
                                            dING_USER_INFO.USER_PHONE = jObjectUser["mobile"].ToString();
                                        }
                                        else
                                        {
                                            dING_USER_INFO.USER_PHONE = "暂无";
                                        }
                                        String RoleID = "";
                                        if (jObjectUser["roles"] != null)
                                        {
                                            foreach (var itemRole in jObjectUser["roles"])
                                            {
                                                RoleID += itemRole["id"].ToString() + ",";
                                            }
                                            dING_USER_INFO.USER_ROLE = RoleID.ToString().TrimEnd(',');
                                        }
                                        else
                                        {
                                            dING_USER_INFO.USER_ROLE = "0";
                                        }
                                        dING_USER_INFOs.Add(dING_USER_INFO);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return dING_USER_INFOs;
        }
    }

    public class DING_ROLE_INFO
    {
        /// <summary>
        /// 钉钉角色组ID
        /// </summary>
        public String ROLE_GROUP_ID { get; set; }
        /// <summary>
        /// 钉钉角色组名称
        /// </summary>
        public String ROLE_GROUP_NAME { get; set; }
        /// <summary>
        /// 钉钉角色ID
        /// </summary>
        public String ROLE_ID { get; set; }
        /// <summary>
        /// 钉钉角色名称
        /// </summary>
        public String ROLE_NAME { get; set; }
    }
    public class DING_DEPT_INFO
    {
        /// <summary>
        /// 钉钉部门ID
        /// </summary>
        public String DING_CODE { get; set; }
        /// <summary>
        /// 钉钉部门名称
        /// </summary>
        public String DEPT_NAME { get; set; }
        /// <summary>
        /// 钉钉上级部门ID
        /// </summary>
        public String PARENT_ID { get; set; }
    }

    public class DING_USER_INFO
    {
        /// <summary>
        /// 钉钉ID
        /// </summary>
        public String USER_DING_ID { get; set; }
        /// <summary>
        /// 钉钉姓名
        /// </summary>
        public String USER_NAME { get; set; }
        /// <summary>
        /// 钉钉电话
        /// </summary>
        public String USER_PHONE { get; set; }
        /// <summary>
        /// 钉钉工号
        /// </summary>
        public String USER_CODE { get; set; }
        /// <summary>
        /// 钉钉职位名称
        /// </summary>
        public String USER_POSITION { get; set; }
        /// <summary>
        /// 钉钉部门编号
        /// </summary>
        public String USER_DEPT { get; set; }
        /// <summary>
        /// 钉钉角色
        /// </summary>
        public String USER_ROLE { get; set; }
    }
}